package com.summer.filesync.security;

import java.time.LocalDateTime;

/** 会话实体类 表示用户的登录会话信息 */
public class Session {
  private final String username;
  private final UserRole role;
  private final LocalDateTime createdAt;
  private LocalDateTime lastAccess;
  private int requestCount;

  public Session(String username, UserRole role, LocalDateTime createdAt) {
    this.username = username;
    this.role = role;
    this.createdAt = createdAt;
    this.lastAccess = createdAt;
    this.requestCount = 0;
  }

  public String getUsername() {
    return username;
  }

  public UserRole getRole() {
    return role;
  }

  public LocalDateTime getCreatedAt() {
    return createdAt;
  }

  public LocalDateTime getLastAccess() {
    return lastAccess;
  }

  public int getRequestCount() {
    return requestCount;
  }

  public void updateLastAccess() {
    this.lastAccess = LocalDateTime.now();
    this.requestCount++;
  }

  /**
   * 检查会话是否活跃（最近一小时内有访问）
   *
   * @return 是否活跃
   */
  public boolean isActive() {
    return lastAccess.isAfter(LocalDateTime.now().minusHours(1));
  }

  /**
   * 获取会话持续时间（分钟）
   *
   * @return 持续时间
   */
  public long getDurationMinutes() {
    return java.time.Duration.between(createdAt, LocalDateTime.now()).toMinutes();
  }

  @Override
  public String toString() {
    return String.format(
        "Session{username='%s', role=%s, createdAt=%s, lastAccess=%s, requestCount=%d}",
        username, role, createdAt, lastAccess, requestCount);
  }
}
